package ldh.im.fxgui.rpc.router;

import com.jfoenix.controls.JFXDialog;
import javafx.application.Platform;
import ldh.im.dto.base.OkResp;
import ldh.im.dto.business.webrtc.WebRtcCancelReq;
import ldh.im.dto.business.webrtc.WebRtcInvitationReq;
import ldh.im.dto.business.webrtc.WebRtcInvitationResultReq;
import ldh.im.fxbase.data.event.AvInvite;
import ldh.im.fxbase.data.event.EventBusFactory;
import ldh.im.fxbase.data.pojo.ImUser;
import ldh.im.fxbase.rpc.service.RpcWebRtcService;
import ldh.im.fxbase.util.*;
import ldh.im.fxgui.util.UiUtil;
import ldh.rpc.util.JsonUtil;
import ldh.rpc.Rpc;
import ldh.rpc.RpcMapper;
import ldh.rpc.exception.RpcException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Closeable;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

/**
 * 接受对方语音、视频邀请
 */
@Rpc
public class WebRtcConsumerRouter {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebRtcConsumerRouter.class);

    /**
     * 接受对方的语音、视频聊天邀请
     * @throws RpcException
     */
    @RpcMapper(path = "serverRedirectWebRtcInvitation", asynHandle = true)
    public void receiveInvitation(WebRtcInvitationReq invitationReq) throws RpcException {
        LOGGER.info("[WebRtc receive invitation], data: {}", JsonUtil.toJson(invitationReq));
        String roomName = invitationReq.getRoomName();
        String userId = invitationReq.getFromUserId();
        ImUser imUser = ImCacheFactory.getInstance().getUser(userId);
        FxThreadUtil.runLater(()->{
            UiUtil.getMainController().switchUserMessage(imUser, (Void1)->{
            });
            AvInvite avInvite = new AvInvite(invitationReq.getFromUserId(), userId, invitationReq.getChatType(), roomName);
            UiUtil.getMainController().webRtcInvite(avInvite);
        });
    }

    /**
     * 接受邀请反馈： 接受 或 拒绝
     * @param invitationResultReq
     * @return
     * @throws RpcException
     */
    @RpcMapper(path = "serverRedirectWebRtcInvitationResult", asynHandle = true)
    public OkResp receiveInvitationResult(WebRtcInvitationResultReq invitationResultReq) throws RpcException {
        LOGGER.info("[WebRtc receive invitation result], data: {}", JsonUtil.toJson(invitationResultReq));
        if (!invitationResultReq.isAccept()) {
            String key1 = "audioRoomStage";
            String key2 = "videoRoomStage";
            boolean isTrue1 = closeStage(key1);
            boolean isTrue2 = closeStage(key2);
            if (isTrue1 || isTrue2) {
                FxThreadUtil.runLater(()->{
                    DialogUtil.alert("语音邀请", invitationResultReq.getToUserId() + "拒绝视频聊天");
                });
            }
        }
        return new OkResp(invitationResultReq.getLocalSeq());
    }

    @RpcMapper(path = "serverRedirectWebRtcCancel", asynHandle = true)
    public OkResp receiveCancel(WebRtcCancelReq cancelReq) throws RpcException {
        LOGGER.info("[WebRtc receive cancel], data: {}", JsonUtil.toJson(cancelReq));
        String key1 = "audioRoomStage";
        String key2 = "videoRoomStage";
        boolean isTrue1 = closeStage(key1);
        boolean isTrue2 = closeStage(key2);
        return new OkResp(cancelReq.getLocalSeq());
    }

    private boolean closeStage(String key) {
        try {
            Closeable closeable = CloseFactory.getInstance().remove(key);
            if (closeable != null) {
                closeable.close();
                return true;
            }
        } catch (Exception e) {
            LOGGER.error("close av stage error", e);
        }
        return false;
    }
}
